from ansys.mapdl import reader as pymapdl_reader
from ansys.mapdl.reader import examples
import os
import vtk

# rst_path：rst文件路径
# vtk_dir：输出vtk文件夹路径
def RstToVtk(rst_path: str, vtk_dir: str):
    # 判断文件是否存在
    is_exist = os.path.exists(rst_path)
    if not is_exist:
        print("[ERROR] Rst(" + rst_path + ") is not exist.")

    vtk_path = ""
    try:
       result = pymapdl_reader.read_binary(rst_path)
       # rst文件名
       rst_file_name = os.path.basename(rst_path)
       file_name, ext = os.path.splitext(rst_file_name)

       vtk_file_name = file_name + ".vtu"
       vtk_path = vtk_dir + "/" + vtk_file_name
       result.save_as_vtk(vtk_path)

       # 读取vtu文件
       reader = vtk.vtkXMLUnstructuredGridReader()
       reader.SetFileName(vtk_path)
       reader.Update()
       read_data = reader.GetOutput()
       field_data = read_data.GetFieldData()
       num_of_arrays = field_data.GetNumberOfArrays()
       for i in range(num_of_arrays):
           field_data.RemoveArray(0)
       writer = vtk.vtkXMLUnstructuredGridWriter()
       writer.SetFileName(vtk_path)
       writer.SetDataModeToAscii()
       writer.SetInputData(read_data)
       writer.Update()
    except:
        print("[ERROR] Rst(" + rst_path + ") to vtk(" + vtk_dir + ") failed.")

    return vtk_path